<template>
  <el-dialog
    v-model="dialogVisible"
    title="基于需求生成YAML脚本"
    width="60%"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="需求内容" prop="requirement_content">
        <el-input
          v-model="formData.requirement_content"
          type="textarea"
          :rows="6"
          placeholder="请输入需求内容描述"
          readonly
        />
      </el-form-item>

      <el-form-item label="测试场景" prop="test_scenarios">
        <div class="scenarios-container">
          <div
            v-for="(scenario, index) in formData.test_scenarios"
            :key="index"
            class="scenario-item"
          >
            <el-input
              v-model="formData.test_scenarios[index]"
              placeholder="请输入测试场景描述"
              class="scenario-input"
            />
            <el-button
              type="danger"
              size="small"
              @click="removeScenario(index)"
              :disabled="formData.test_scenarios.length <= 1"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          <el-button
            type="primary"
            size="small"
            @click="addScenario"
            style="margin-top: 8px;"
          >
            <el-icon><Plus /></el-icon>
            添加场景
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="额外要求">
        <el-input
          v-model="formData.additional_requirements"
          type="textarea"
          :rows="3"
          placeholder="请输入额外的测试要求（可选）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleGenerate" :loading="generating">
          <el-icon><Star /></el-icon>
          生成YAML脚本
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Plus, Star } from '@element-plus/icons-vue'
import { requirementsApi } from '../../api/requirements'
import { generateYamlScript } from '../../api/uiAutomation'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  requirementId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'generated'])

// 响应式数据
const formRef = ref()
const generating = ref(false)

// 表单数据
const formData = reactive({
  requirement_content: '',
  test_scenarios: [''],
  additional_requirements: ''
})

// 表单验证规则
const formRules = {
  requirement_content: [
    { required: true, message: '需求内容不能为空', trigger: 'blur' }
  ],
  test_scenarios: [
    {
      validator: (rule, value, callback) => {
        const validScenarios = value.filter(scenario => scenario.trim())
        if (validScenarios.length === 0) {
          callback(new Error('请至少添加一个测试场景'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听器
watch(() => props.visible, (visible) => {
  if (visible && props.requirementId) {
    loadRequirement()
  }
})

// 方法
const loadRequirement = async () => {
  try {
    const response = await requirementsApi.getRequirement(props.requirementId)
    if (response.id) {
      formData.requirement_content = response.content || response.description || ''
    }
  } catch (error) {
    console.error('加载需求详情失败:', error)
    ElMessage.error('加载需求详情失败')
  }
}

const addScenario = () => {
  formData.test_scenarios.push('')
}

const removeScenario = (index) => {
  if (formData.test_scenarios.length > 1) {
    formData.test_scenarios.splice(index, 1)
  }
}

const handleClose = () => {
  dialogVisible.value = false
  // 重置表单
  formData.requirement_content = ''
  formData.test_scenarios = ['']
  formData.additional_requirements = ''
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleGenerate = async () => {
  try {
    await formRef.value.validate()
    
    // 过滤空的测试场景
    const validScenarios = formData.test_scenarios.filter(scenario => scenario.trim())
    
    if (validScenarios.length === 0) {
      ElMessage.warning('请至少添加一个有效的测试场景')
      return
    }
    
    generating.value = true
    
    const requestData = {
      requirement_id: props.requirementId,
      requirement_content: formData.requirement_content,
      test_scenarios: validScenarios,
      additional_requirements: formData.additional_requirements || null
    }
    
    const response = await generateYamlScript(requestData)
    
    if (response.success) {
      emit('generated', response.data)
      handleClose()
    } else {
      ElMessage.error(response.message || 'YAML脚本生成失败')
    }
  } catch (error) {
    console.error('生成YAML脚本失败:', error)
    ElMessage.error('生成YAML脚本失败')
  } finally {
    generating.value = false
  }
}
</script>

<style lang="scss" scoped>
.scenarios-container {
  .scenario-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    gap: 8px;
    
    .scenario-input {
      flex: 1;
    }
  }
}

.dialog-footer {
  text-align: right;
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px;
  }
}
</style>
